package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.user.entity.MenuEntity;
import com.shuda.business.user.mapper.MenuMapper;
import com.shuda.business.user.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单服务实现类
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {

    @Override
    public List<MenuEntity> getMenuList(QueryWrapper<MenuEntity> queryWrapper) {
        return list(queryWrapper);
    }

    @Override
    public List<MenuEntity> getMenuListByRoleId(Long roleId) {
        // 这里需要根据角色ID查询对应的菜单列表
        // 由于缺少角色菜单关联表，这里返回空列表
        return List.of();
    }

    @Override
    public List<MenuEntity> getMenuTree() {
        LambdaQueryWrapper<MenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuEntity::getStatus, "0");
        wrapper.orderByAsc(MenuEntity::getParentId).orderByAsc(MenuEntity::getOrderNum);
        List<MenuEntity> menuList = list(wrapper);
        return buildMenuTree(menuList, 0L);
    }

    @Override
    public List<MenuEntity> getMenuTreeByRoleId(Long roleId) {
        List<MenuEntity> roleMenus = getMenuListByRoleId(roleId);
        return buildMenuTree(roleMenus, 0L);
    }

    @Override
    public void createMenu(MenuEntity menu) {
        save(menu);
    }

    @Override
    public void updateMenu(MenuEntity menu) {
        updateById(menu);
    }

    @Override
    public void deleteMenu(Long id) {
        removeById(id);
    }

    @Override
    public void updateMenuStatus(Long id, String status) {
        MenuEntity menu = getById(id);
        if (menu != null) {
            menu.setStatus(status);
            updateById(menu);
        }
    }

    @Override
    public void updateMenuSort(List<MenuEntity> menus) {
        if (menus != null) {
            for (MenuEntity menu : menus) {
                updateById(menu);
            }
        }
    }

    private List<MenuEntity> buildMenuTree(List<MenuEntity> menuList, Long parentId) {
        return menuList.stream()
                .filter(menu -> parentId.equals(menu.getParentId()))
                .map(menu -> {
                    menu.setChildren(buildMenuTree(menuList, menu.getId()));
                    return menu;
                })
                .collect(Collectors.toList());
    }
}